<?php
// +----------------------------------------------------------------------
// | Description: Members
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------
// | Date: 2018-01-24 16:50:46
// +----------------------------------------------------------------------

namespace app\client\controller;

use app\common\controller\Rest;
use EasyWeChat\Factory;

class Members extends Rest
{
    public $modelName = 'Member';
    public function _initialize()
    {
        parent::_initialize();
        // $this -> abort(!$this -> isClient, 'Permission denied', 403);
    }

    public function index()
    {
        if ($this->param['defaultAddress']) {
            $this->checkedAddress();
        } else {
            if ($this->isClient) {
                $this->param['Id'] = $this->param['UserId'];
                unset($this->param['UserId']);
                self::$model->setParam($this->param);
            }
            $data = self::$model->getDataList($this->param);
            $this->jsonData($data);
        }
    }

    public function update()
    {
        if ($this->isClient) {
            $this->param['Id'] = $this->param['UserId'];
            unset($this->param['UserId']);
            $res = self::$model->updateDataById($this->param, $this->param['Id']); // 客户端访问
        } else {
            $res = self::$model->updateDataById($this->param, $this->param['id']);
        }

        $this->checkRes($res, '编辑成功', self::$model->getError());
    }

    public function enables()
    {
        $res = self::$model->enableDatas($this->param['ids'], $this->param['status'], 'Enabled');
        $this->checkRes($res, '批量操作成功', self::$model->getError());
    }

    public function checkedAddress()
    {
        $data = self::$model->address($this->param);
        $this->jsonData($data, self::$model->getError());
    }

    /**
     * 登录之后根据原密码修改密码
     *
     * @return void
     */
    public function modifyPass()
    {
        $memberInfo = self::$model->get($this->param['UserId']);
        $this->abort(user_md5($this->param['oldPass'], $memberInfo['PasswordSalt']) === $memberInfo['Password'], '原密码错误!');
        try {
            self::$model->where(['Id' => $this->param['UserId']])->update(['Password' => user_md5($this->param['newPass'], $memberInfo['PasswordSalt'])]);
        } catch (\Exception $e) {
            $this->abort(false, $e->getMessage());
        }
        $this->jsonData('修改成功!');
    }

    /**
     * 获取二维码图片接口
     *
     * @return void
     */
    public function qrcode()
    {
        // $config = [
        //     'app_id' => 'wx5876e5d51f69fbd9',
        //     // 'secret' => '9be0f0536ec0561d3731197729aa341e',
        //     'secret' => '5894359d5e661151a54dafef351144ab',
        //     'token' => 'ceshi', // Token

        //     // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        //     'response_type' => 'array',

        //     'log' => [
        //         'level' => 'debug',
        //         'file' => './wechat2.log',
        //     ],
        // ];

        // $app = Factory::officialAccount($config);

        // $result = $app->qrcode->forever($this -> param['UserId']); // 或者 $app->qrcode->forever("foo");
        // // Array
        // // (
        // //     [ticket] => gQFD8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTmFjVTRWU3ViUE8xR1N4ajFwMWsAAgS2uItZAwQA6QcA
        // //     [url] => http://weixin.qq.com/q/02NacU4VSubPO1GSxj1p1k
        // // )
        // $this -> abort($result['ticket'], '获取失败!');
        // $ticket = $result['ticket'];
        // // 获取二维码网址
        // $url = $app->qrcode->url($ticket);
        // https://api.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
        // 获取二维码内容
        $id = $this->param['UserId'];
        // echo $url;
        $this->jsonData($id);
        // $content = file_get_contents($url); // 得到二进制图片内容
        // file_put_contents(__DIR__ . '/code.jpg', $content); // 写入文件

    }

    public function isSub()
    {
        $openId = self::$model->where(['Id' => $this->param['UserId']])->value('OpenId');
        $config = [
            'app_id' => 'wx5876e5d51f69fbd9',
            // 'secret' => '9be0f0536ec0561d3731197729aa341e',
            'secret' => '5894359d5e661151a54dafef351144ab',
            'token' => 'ceshi', // Token

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => './wechat2.log',
            ],
        ];

        $app = Factory::officialAccount($config);
        try{
            $user = $app->user->get($openId);
        }catch(\Exception $e){
            $this->abort(false, $e->getMessage());
            $this->jsonData('0'); // TODO 如果这里报错了 用户应该是没有关注
        }
        $this->jsonData($user['subscribe']);
        if($user){
            $this->jsonData('1');
        }else{
            $this->jsonData('0');
        }
        
    }

    // public function children(){
    //     $level = 1;
    //     $pid = 'ReferUserId';

    // }

    // public function getChildId($ReferUserIds, $level = 3)
    // {
    //     $data = self::$model -> where('ReferUserId', 'in', $ReferUserIds) -> field('Id') -> select();
    //     $ids = [];
    //     foreach($data as $k => $v){
    //         $ids[] = $v['Id'];
    //     }
    //     return $ids;
    // }

    public function level_one()
    {
        $data = self::$model->where(['ReferUserId' => $this->param['UserId']])->field('CellPhone,CreateDate,HeadImg')->select();
        if (!$data) {
            $data = [
                'list' => [],
                'dataCount' => 0,
            ];
        } else {
            $data = [
                'list' => $data,
                'dataCount' => 0,
            ];
        }
        $this->jsonData($data);
    }

    public function level_tow()
    {

        $data = self::$model->where(['ReferUserId' => $this->param['UserId']])->field('Id')->select();
        $ids = $this->getids($data);
        if ($ids) {
            $res = self::$model->where('ReferUserId', 'in', $ids)->field('CellPhone,CreateDate,HeadImg')->select();
            if (!$res) {
                $res = [
                    'list' => [],
                    'dataCount' => 0,
                ];
            } else {
                $res = [
                    'list' => $res,
                    'dataCount' => 0,
                ];
            }

            $this->jsonData($res);
        } else {
            $res = [
                'list' => [],
                'dataCount' => 0,
            ];
            $this->jsonData($res);
        }

    }

    public function level_three()
    {
        $data = self::$model->where(['ReferUserId' => $this->param['UserId']])->field('Id')->select();
        $ids1 = $this->getids($data);
        if ($ids1) {
            $data2 = self::$model->where('ReferUserId', 'in', $ids1)->field('Id')->select();
            $ids2 = $this->getids($data2);
            if ($ids2) {
                $res = self::$model->where('ReferUserId', 'in', $ids2)->field('CellPhone,CreateDate,HeadImg')->select();
                if (!$res) {
                    $res = [
                        'list' => [],
                        'dataCount' => 0,
                    ];
                } else {
                    $res = [
                        'list' => $res,
                        'dataCount' => 0,
                    ];
                }
                $this->jsonData($res);
            }
        }
        $res = [
            'list' => [],
            'dataCount' => 0,
        ];
        $this->jsonData($res);

    }

    private function getids($data)
    {
        $ids = [];
        foreach ($data as $k => $v) {
            $ids[] = $v['Id'];
        }
        return $ids;
    }

}
